#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import re

from Ump.common import log
from Ump.common import exception
from Ump.objs.db import models
from Ump.objs.db.models import SysconfigForUMP, ScheduleJob
from Ump.objs.manager_base import Manager
from Ump.objs.session_wrapper import enable_log_and_session
from Ump.objs.session_wrapper import _sw
from Ump.schedule.api import ScheduleApi
from Ump.objs.recover.manager import  RecoverManager


LOG = log.get_log('Ump.objs.sysconfigforump.manager')


@models.add_model(models.SysconfigForUMP)
class SysconfigForUMPManager(Manager):
    def __init__(self):
        super(SysconfigForUMPManager, self).__init__()

    @enable_log_and_session(resource='settings', event='update', )
    def update(self, _logger, params):
        sysconfig_for_ump_id = params.get('id')
        sysconfig_for_ump = SysconfigForUMP.query.get(sysconfig_for_ump_id)
        if not sysconfig_for_ump:
            raise exception.NotFound(_id=sysconfig_for_ump_id)

        name = sysconfig_for_ump.name.split('.')   # name[0] is `group_name` field in database, name[1] is the `name` field
        value_setting = params.get('value')

        detail = "changed from %s to %s" % (sysconfig_for_ump.value_setting, value_setting)
        _logger.update_props(oplog_obj=sysconfig_for_ump.name, detail=detail)


        schedule_job = ScheduleJob.query.filter_by(group_name=name[0]).first()
        schedule_api = ScheduleApi()
        if name[1] == 'qos_limit':
            value_setting = self._check_bandwith(params)
            self.data_recover_deal(value_setting)
        if name[1] == 'threshold':
            value_setting = self._check(name[0], value_setting)
        elif name[1] == 'enabled':
            enabled = self._check_enabled(value_setting)
            _values = {'enabled':  enabled}
            schedule_api.update_job(schedule_job.id, _values)
        elif name[1] == 'interval':
            interval = self._check_interval(value_setting)
            _values = {'every': interval}
            schedule_api.update_job(schedule_job.id, _values)
        elif name[1] == 'list':
            value_setting = self._check_mail(value_setting)
        elif name[1] == 'start_date':
            _values = {'start_date': value_setting}
            schedule_api.update_job(schedule_job.id, _values)
        else:
            pass

        values = {
            'value_setting': value_setting
        }

        sysconfig_for_ump.update(values)

    def _check_mail(self, value):
        if '\xef\xbc\x8c' in value:
            raise  exception.InvalidParameter('pleass use comma(,) of english do not use comma(,) of china')
        if '\xef\xbc\x9b' in value:
            raise  exception.InvalidParameter('pleass use comma of english,do not use semicolon(;) ')
        mail_list = str(value).split(',')
        valid_ = []
        for mail in mail_list:
            if re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", mail):
                valid_.append(mail)
            else: valid_.append('error')
        print  valid_
        if 'error' in valid_:
            raise exception.InvalidParameter("Please check your value!")
        else:
             return value

    def _check_interval(self, value):
        if re.compile('^(\d+)$').match(str(value)):
            return value
        raise exception.InvalidParameter("Interval value should be only integer number!")

    def _check_bandwith(self, params):
        value = float(params.get('value'))
        if value > 0:
            return value 
        if value < 0:
            if value != -1:
                raise exception.ParameterWrong('必须为-1或者非零意外的任意数值')
            return  value
        else:
            raise exception.ParameterWrong('必须为-1或者为非零意外的任意数值')
    def _check_enabled(self, value):
        if value in ['false', 'False', False]:
            return False
        elif value in ['true', 'True', True]:
            return True
        else:
            raise exception.InvalidParameter("Please check your value!")

    def _check(self, name, value):
        regexp_map = {
            'disk_capacity': '^([1-9]\d?|100)$',
            'volume_number': '^(\d+)$',
            'CPU_usage':'^([1-9]\d?|100)$',
            'memory_usage':'^([1-9]\d?|100)$',
            'network_bandwidth':'^(\d+)$',
            'latency':'^(\d+)$',
            'mail_receive': '^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$',
        }

        regexp = regexp_map.get(name)

        if regexp is None:
            return value

        if re.compile(regexp).match(str(value)):
            return value
        raise exception.InvalidParameter("Please check your value!")

    def data_recover_deal(self, qos_maxbw):
        cluster = _sw.get_cluster()
        ips = [host.ip for host in cluster.hosts]

        qos_maxbw = float(qos_maxbw)
        qos_policy = 1 if qos_maxbw < 0 else 0
        kwargs = {
                'hosts': ips,
                'qos_maxbw': qos_maxbw,
                'qos_policy': qos_policy,
            }
        recover_manager = RecoverManager()
        recover_manager.qos(kwargs)


if __name__ == '__main__':
    snm = SysconfigForUMPManager()
    snm.update()
